from rest_framework.generics import GenericAPIView, RetrieveUpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from six_it.models import User
from young11_11.serializers.users import UserSerializer, UserPasswordSerializer
from rest_framework_jwt.utils import jwt_decode_handler


class UserInfoView(RetrieveUpdateAPIView):
    permission_classes = [IsAuthenticated]

    # 指定视图所使用的序列化器类
    serializer_class = UserSerializer
    # 指定视图所使用的查询集
    queryset = User.objects.all()

    def get(self, request):
        """
        获取用户数据:
        1. 查询用户数据
        2. 将用户数据序列化并返回
        """
        # 获取登陆的用户
        # token = request.META.get('HTTP_AUTHORIZATION')[4:]
        # token_user = jwt_decode_handler(token)
        #
        # user_id = token_user['user_id']  # 获取用户id
        #
        # # 1. 获取用户数据
        # users = User.objects.get(id = user_id)

        # users = User.objects.get(id=request.user.id)

        user = self.request.user
        replies = user.replies.all()
        user.answer_question = []
        for item in replies:
            if item.type == 2:  # 回答的评论
                user.answer_question.append(item)
        serle = self.serializer_class(user)
        return Response(serle.data)

    def put(self, request):
        """
        修改个人信息
        """
        users = request.user
        # 反序列化-数据校验
        serializer = self.get_serializer(users, data=request.data)
        serializer.is_valid(raise_exception=True)

        # 反序列化-数据保存(save内部会调用序列化器类的update方法)
        serializer.save()

        return Response(serializer.data)


class ChangePasswordView(GenericAPIView):
    permission_classes = [IsAuthenticated]

    queryset = User.objects.all()
    serializer_class = UserPasswordSerializer

    def put(self, request):
        users = request.user
        # 反序列化-数据校验
        serializer = self.get_serializer(users, data=request.data)
        serializer.is_valid(raise_exception=True)

        # 反序列化-数据保存(save内部会调用序列化器类的update方法)
        serializer.save()

        return Response(serializer.data)


class AttentionView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, id):
        user = self.request.user

        idol = User.objects.get(id=id)
        idol.fans.add(user)
        idol.save()
        return Response({
            "message": "成功关注",
            "success": True
        })

    def delete(self, request, id):
        user = self.request.user
        idol = User.objects.get(id=id)
        idol.fans.remove(user)
        return Response({
            "message": "取消关注",
            "success": True
        })
